import { setItem, getItem, removeItem } from '@/utils/save'
import { loginService, logoutService } from '@/api/login'

const user = {
  state: {
    user_info: getItem('user_info'),
    username: '',
    random: Math.random(),
    loginVisual:false,
    dialogType:false,
    randType:0,
  },
  getters:{
    typeRand(state) {
      return state.randType
    },
    isGuest(state) {
      if (null == state.user_info) { 
        state.user_info = getItem('user_info')
      }

      if (state.user_info)  return false
      else                  return true
    },
    user_name(state) {
      if (state.user_info) {
        return state.user_info.username
      }
      return ''
    },
    user_id(state) {
      if (state.user_info) {
        return state.user_info.user_id
      }
      return 0
    },
    msg_number(state) {
      if (state.user_info) {
        return state.user_info.message_count
      }
      return 0
    },
    img_update(state) {
      return state.random
    },
    login_visual(state) {
      return state.loginVisual
    },
    dialog_type(state) {
      return state.dialogType
    }
  },
  mutations: {
    setLoginDlg: (state, {visual, type}) => {
      state.loginVisual = visual
      state.dialogType = type
    },
    setOpposite: (state) => {
      state.dialogType = !state.dialogType
    },   
    setImgUpdate: (state) => {
      state.random = Math.random()
    },
    setMsgRead: (state, total) => {
      state.user_info.message_count = total
      setItem('user_info', state.user_info, true)
    },
    setUserInfo: (state, userInfo) => {
      setItem('user_info', userInfo, true)
      state.user_info = userInfo
      state.random = Math.random()
    },
    clearUserInfo: (state) => {
      removeItem('user_info')
      state.user_info = null
    },
    setRandType:(state, rType) => {
      state.randType = rType
    },
  },
  actions: {
    async userLogin({ commit, state }, info) {
      let resp = await loginService(info)
      if (!resp) {
        return resp | {}
      }

      if (0 == resp.result && resp.data) {
        delete resp.data['mark']
        commit('setUserInfo', resp.data)
      }

      return resp
    },
    async userLogout({ commit, state }) {
      const resp = await logoutService({})
      commit('clearUserInfo')
      return resp
    }
  }
}

export default user